﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace Depositario
{
    public partial class Form1 : Form
    {
        private string _unit,_content;
        private bool _capoGruppo;
        private string[] _tutte;
        private int _x, _y;

        public Form1()
        {
            InitializeComponent();
        }

        private void Button4Click(object sender, EventArgs e)
        {
            var pwd = textBox3.Text.Trim();
            var usr = textBox4.Text.Trim();
            if (pwd == "" && usr == "") return;
            if (usr == "")
            {
                ShowMessage("Non hai inserito l'user!", "Input non valido");
                return;
            }
            if (pwd == "")
            {
                ShowMessage("Non hai inserito la password!", "Input non valido");
                return;
            }
            button4.Enabled = false;
            if (button4.Text=="Connetti" && !backgroundWorker1.IsBusy)
            {
                statusStrip1.Items[0].Text = "Tentativo di connessione in corso...";
                backgroundWorker1.RunWorkerAsync("login");
            }
            if (button4.Text != "Disconnetti") return;
            textBox3.Enabled = true;
            textBox4.Enabled = true;
            button4.Text = "Connetti";
            button4.Enabled = true;
            tabControl1.TabPages[0].Text = "Login";
            UpdateStatusTrip(textBox4.Text + " disconnesso");
            tabControl1.TabPages[1].Enabled = false;
        }
        private void Button2Click(object sender, EventArgs e)
        {
            long id=0;
            dataGridView1.Rows.Clear();
            var val = textBox1.Text.ToLower().Trim();
            char tapullo='a';
            if (comboBox2.SelectedIndex == 2)
            {
                tapullo=val.First();
                if (tapullo == '<' )
                    val =val.Replace("<","");
                if (tapullo == '>')
                    val = val.Replace(">", "");
            }
            if (comboBox2.Text == "" || val=="") return;
            if (comboBox2.Text != "Item")
            {
                try
                {
                    id=long.Parse(val);
                }
                catch (Exception)
                {
                    ShowMessage("Non hai messo un numero!", "Input non valido");
                    return;
                }
            }
            var cerca = comboBox2.Text == "Id" || comboBox2.Text == "Quanti" ? id : 0;
            
            using (var context = new DepositarioEntities())
            {     
                var myEvents = from q in context.magazzino
                               where comboBox2.Text == "Id" ? q.Id == cerca :
                                      comboBox2.Text == "Item" ? q.Item == val.ToLower() :
                                        (tapullo == '<' ? q.Quanti < cerca : tapullo == '>' ? q.Quanti > cerca : q.Quanti == cerca)
                                        && q.Unita == _unit
                               select q;
                UpdateStatusTrip(myEvents.Count() + " trovati");
                if (!myEvents.Any())
                {
                    ShowMessage("Nessun oggetto trovato!", "Notifica");
                    return;
                }
                RiempiTabItem(myEvents);
            }
        }
        
        private void TabControl1SelectedIndexChanged(object sender, EventArgs e)
        {
            //tabControl1.MinimumSize = new Size(1, 1);
            
           
            //Height = tabControl1.SelectedIndex == 1 || tabControl1.SelectedIndex == 2 ? 648 : 780;
            //Width = tabControl1.SelectedIndex == 1 || tabControl1.SelectedIndex == 2 ? 991 : 735;
           
            MinimumSize = tabControl1.SelectedIndex == 0 ? new Size(575, 350) : new Size(928, 607);
            Size = tabControl1.SelectedIndex == 0 ? new Size(575, 350) : new Size(928, 607);
            AutoSizeMode = tabControl1.SelectedIndex == 0 ? AutoSizeMode.GrowAndShrink : AutoSizeMode.GrowOnly;
            FormBorderStyle = tabControl1.SelectedIndex == 0 ? FormBorderStyle.FixedSingle : FormBorderStyle.Sizable;
            MaximizeBox = tabControl1.SelectedIndex != 0;
            dataGridView1.Visible=label4.Visible = tabControl1.SelectedIndex != 0;
            //AutoSize = tabControl1.SelectedIndex == 1 || tabControl1.SelectedIndex == 2;
            //MaximumSize = tabControl1.SelectedIndex == 0 ? new Size(580, 355) : new Size(0, 0);

            if (WindowState == FormWindowState.Maximized)
            {
                WindowState = FormWindowState.Normal;
            }
            
            //Width = tabControl1.SelectedIndex == 0?  580:928;
            //Height = tabControl1.SelectedIndex == 0 ? 1:1 ;
            //label6.Text = MinimumSize.Width.ToString() + MinimumSize.Height.ToString() + " " + Size.Width + Size.Height;
            CenterToScreen();
        }

        private void Form1Load(object sender, EventArgs e)
        {
            Height = 350;
            Width = 580;
            tabControl1.TabPages[1].Enabled = false;
            CenterToScreen();
            var oggi = DateTime.Now;
            numericUpDown3.Value = numericUpDown6.Value = oggi.Day;
            numericUpDown4.Value =  numericUpDown7.Value = oggi.Month;
            numericUpDown5.Maximum = numericUpDown8.Maximum = oggi.Year;
            numericUpDown5.Value = numericUpDown8.Value = oggi.Year;
            label4.Visible = dataGridView1.Visible = false;
        }

        private void Button1Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.magazzino 
                                   where q.Unita==_unit
                                   select q ;
                    RiempiTabItem(myEvents);
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void RiempiTabItem(IEnumerable<magazzino> collection)
        {
            foreach (var a in collection)
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = a.Id;
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = PrimaM(a.Item);
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = a.Quanti;
            }
        }

        private void ComboBox5MouseClick(object sender, MouseEventArgs e)
        {
            Completa(comboBox5);
            button6.Enabled = true;
        }

        private void ComboBox4MouseClick(object sender, MouseEventArgs e)
        {
            comboBox4.Items.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {

                    var r = from q in context.ragazzi
                            where q.Unita == _unit
                            select new { c = q.Cognome, n = q.Nome, cod = q.Codice };
                    foreach (var s in r)
                    {
                        comboBox4.Items.Add(PrimaM(s.n)+"  "+PrimaM(s.c)+(s.cod==null? "" : "  ("+s.cod+ ")"));
                    }
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void ComboBox3MouseClick(object sender, MouseEventArgs e)
        {
            Completa(comboBox3);
        }

        private void Completa(ComboBox comboBox)
        {
            comboBox.Items.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {

                    var r = from q in context.magazzino
                            where q.Unita == _unit
                            select q.Item;
                    foreach (var s in r)
                        comboBox.Items.Add(PrimaM(s));
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void CompletaRag(ComboBox comboBox)
        {
            comboBox.Items.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {

                    var r = from q in context.ragazzi
                            where q.Unita == _unit
                            select q.Nome + "  " + q.Cognome;
                    foreach (var s in r)
                        comboBox.Items.Add(PrimaM(s));
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void ComboBox5SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                using (var context = new DepositarioEntities())
                {

                    var r = (from q in context.magazzino
                             where q.Item == comboBox5.Text.ToLower() && q.Unita == _unit
                            select q.Quanti).First();//dato che sappiamo che Item e' chiave primaria
                    numericUpDown1.Maximum = r>0?r:1; 
                    button6.Enabled = r != 0;
                    numericUpDown1.Value = 1;
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void Button5Click(object sender, EventArgs e)
        {
            try
            {
                using (var context = new DepositarioEntities())
                {

                    var r = (from q in context.magazzino
                             where q.Item == comboBox3.Text.ToLower() && q.Unita == _unit
                             select  q);
                    var te = r.First();
                    context.magazzino.Remove(te);
                    context.SaveChanges();
                    UpdateStatusTrip("\"" + comboBox3.Text + "\" tolto dal magazzino");
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
            dataGridView1.Rows.Clear();
            SvuotaCombo(0);
        }

        private static void ShowMessage(string msg, string title)
        {
            MessageBox.Show(msg,title);
        }

        private static DialogResult ShowMessageWithConfirm(string msg, string title)
        {
            return MessageBox.Show(msg,title,MessageBoxButtons.YesNo);
        }

        private static void Errconnessione()
        {
            ShowMessage("Connessione a internet non riuscita", "Errore di rete");
        }

        private void UpdateStatusTrip(string text)
        {
            statusStrip1.Items[0].Text = text;
        }

        private void Button7Click(object sender, EventArgs e)
        {
            var formattato = textBox5.Text.ToLower().Trim();
            if (formattato == "")
                return;
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var ris = from q in context.magazzino
                              where q.Item == formattato && q.Unita == _unit
                              select q;
                    if (ris.Any())
                    {
                        ris.First().Quanti += (int)numericUpDown2.Value;
                        UpdateStatusTrip("\"" + formattato + "\" aggiornato nel magazzino");
                    }
                    else
                    {
                        var u = new magazzino
                                    {
                                        Item = formattato,
                                        Quanti = (int) numericUpDown2.Value,
                                        Unita = _unit
                                    };
                        context.magazzino.Add(u);
                        UpdateStatusTrip("\"" + formattato + "\" aggiunto nel magazzino");
                    }
                    context.SaveChanges();
                    textBox5.Text = "";
                    numericUpDown2.Value = 0;
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
            dataGridView1.Rows.Clear();
            SvuotaCombo(0);
        }

        private void Button12Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            var nome = textBox8.Text.ToLower().Trim();
            var cognome = textBox7.Text.ToLower().Trim(); 
            if (nome == "" && cognome == "") return;
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.ragazzi
                                   where cognome!=""? nome!=""? cognome == q.Cognome && nome == q.Nome :
                                   cognome.ToLower() == q.Cognome : nome.ToLower() == q.Nome && q.Unita == _unit
                                   select q;
                    UpdateStatusTrip(myEvents.Count() + " trovati");
                 if (!myEvents.Any())
                    {
                        ShowMessage("Nessun ragazzo trovato!", "Notifica");
                        return;
                    }
                    RiempiTabRagazzi(myEvents);
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void RiempiTabRagazzi(IEnumerable<ragazzi> ragazzi)
        {
            var chk = new DataGridViewCheckBoxColumn {HeaderText = "Censito", ReadOnly = !_capoGruppo};
            dataGridView1.Columns.RemoveAt(3);
            dataGridView1.Columns.Add(chk);
            foreach (var a in ragazzi)
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = a.Codice == null ? "-" : a.Codice.ToString();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = PrimaM(a.Nome);
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = PrimaM(a.Cognome);
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = a.Censimento;
                if (a.Censimento)
                    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].ReadOnly = true;
               
               
                
                //dataGridView1.Columns.Add(cmb);
            }
        }

        private void TabControl2SelectedIndexChanged(object sender, EventArgs e){
            SvuotaComboAll();
            UpdateStatusTrip("");
            dataGridView1.Rows.Clear();
            switch (tabControl2.SelectedIndex)
            {
                case 0:
                    dataGridView1.Columns[0].ReadOnly = true;
                    dataGridView1.Columns[1].ReadOnly = false;
                    dataGridView1.Columns[2].ReadOnly = true;
                    dataGridView1.Columns[0].HeaderText = "Id";
                    dataGridView1.Columns[1].HeaderText = "Item";
                    dataGridView1.Columns[2].HeaderText = "Quantita'";
                    // var dfv =
                    //if(dataGridView1.Columns.Count>3)
                    dataGridView1.Columns.RemoveAt(3);
                    //dataGridView1.Columns.Remove(dataGridView1.Columns[3].HeaderText);
                    textBox1.Text = textBox5.Text = "";
                    comboBox2.SelectedIndex = comboBox3.SelectedIndex = comboBox4.SelectedIndex = comboBox5.SelectedIndex = - 1;
                    numericUpDown1.Value = 1;
                    numericUpDown2.Value = 0;
                    var y = groupBox6.Height +
                    ((groupBox5.Location.Y + groupBox5.Height) / 2 - groupBox6.Height - groupBox1.Height) / 2;
                    var y2 = (groupBox5.Location.Y + groupBox5.Height) / 2 +
                    ((groupBox5.Location.Y + groupBox5.Height) / 2 - groupBox5.Height - groupBox4.Height) / 2;
                    groupBox1.Location = y > 110 ? new Point(7, y) : new Point(7, 110);
                    if (y2 > 221)
                        groupBox4.Location = new Point(7, y2);
                    break;
                case 1:
                    dataGridView1.Columns[0].ReadOnly = false;
                    dataGridView1.Columns[1].ReadOnly = false;
                    dataGridView1.Columns[2].ReadOnly = false;
                    dataGridView1.Columns[0].HeaderText = "Codice";
                    dataGridView1.Columns[1].HeaderText = "Nome";
                    dataGridView1.Columns[2].HeaderText = "Cognome";
                    if (dataGridView1.Columns.Count < 4)
                        dataGridView1.Columns.Add("Data", "Censito");
                    else
                        dataGridView1.Columns[3].HeaderText = "Censito";
                    textBox6.Text = textBox7.Text = textBox8.Text = textBox10.Text = textBox11.Text = "";
                    comboBox6.SelectedIndex = comboBox9.SelectedIndex = comboBox10.SelectedIndex = -1;
                    var ya = groupBox7.Height +
                    ((groupBox8.Location.Y + groupBox8.Height) / 2 - groupBox7.Height - groupBox10.Height) / 2;
                    var y2a = (groupBox8.Location.Y + groupBox8.Height) / 2 +
                    ((groupBox8.Location.Y + groupBox8.Height) / 2 - groupBox8.Height - groupBox9.Height) / 2;
                    groupBox10.Location = ya>110 ? new Point(7, ya) : new Point(7, 110);
                    if (y2a > 221)
                        groupBox9.Location = new Point(7, y2a);
                    break;
                case 2:
                    dataGridView1.Columns[0].HeaderText = "Item";
                    dataGridView1.Columns[1].HeaderText = "Quantita'";
                    dataGridView1.Columns[2].HeaderText = "Ragazzo";
                    if (dataGridView1.Columns.Count < 4)
                        dataGridView1.Columns.Add("Data", "Data");
                    else
                        dataGridView1.Columns[3].HeaderText = "Data";
                    dataGridView1.Columns[0].ReadOnly = true;
                    dataGridView1.Columns[1].ReadOnly = true;
                    dataGridView1.Columns[2].ReadOnly = true;
                    dataGridView1.Columns[3].ReadOnly = true;
                    comboBox1.SelectedIndex = comboBox7.SelectedIndex = -1;
                    var oggi = DateTime.Now;
                    numericUpDown3.Value = numericUpDown6.Value = oggi.Day;
                    numericUpDown4.Value =  numericUpDown7.Value = oggi.Month;
                    numericUpDown5.Maximum = numericUpDown8.Maximum = oggi.Year;
                    numericUpDown5.Value = numericUpDown8.Value = oggi.Year;
                    radioButton1.Checked = radioButton2.Checked = false;
                    radioButton3.Checked = true;
                    break;
                default:
                    return;
            } 
        }

        private void Button8Click(object sender, EventArgs e)
        {
            var cod = (long)0;
            var nome = textBox6.Text.ToLower().Trim();
            var cognome = textBox10.Text.ToLower().Trim();
            var codi = textBox11.Text.Trim();
            if (nome == "" || cognome == "")
                return;
            if (nome.Contains("  ") || cognome.Contains("  "))
            {
                ShowMessage("Non puoi mettere 2 spazi consecutivi", "Input non valido");
                return;
            } 
            if (textBox11.Text != "")
            {
                try
                {
                    cod = Int64.Parse(codi);
                }
                catch (Exception)
                {
                    ShowMessage("Non hai messo un numero!", "Input non valido");
                    return;
                }
            }
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var u = new ragazzi
                    {
                        Nome = nome,
                        Cognome = cognome,
                        Unita = _unit,
                    };
                    if (cod != 0)
                        u.Codice = cod;
                    context.ragazzi.Add(u);
                    UpdateStatusTrip("\"" + nome+ " "+ cognome + "\" aggiunto.");
                    context.SaveChanges();
                    textBox6.Text = textBox10.Text = textBox11.Text = "";
                }
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException)
            {
                ShowMessage("Inserimento non valido: Utente gia' presente", "Input non valido");
            }
            catch (Exception)
            {
                Errconnessione();
            }
            dataGridView1.Rows.Clear();
            SvuotaCombo(1);
        }

        private void Button11Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.ragazzi
                                   where q.Unita == _unit
                                   select q;
                    RiempiTabRagazzi(myEvents);
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void Button10Click(object sender, EventArgs e)
        {
            if(comboBox10.Text=="")
                return;
            var result1 = ShowMessageWithConfirm("Sei sicuro di cancellare " + comboBox10.Text + "?", "Conferma");
            if (result1 == DialogResult.No)
                return;
            var nomeECognome = comboBox10.Text;
            var t = new string[1];
            t[0] = "  ";
            var pezzi = nomeECognome.Split(t, StringSplitOptions.None);
            var a1 = pezzi[1];
            var b = pezzi[0];
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var r = (from q in context.ragazzi
                             where q.Nome == b.ToLower()  && q.Cognome == a1.ToLower() && q.Unita == _unit
                             select q);
                    context.ragazzi.Remove(r.First());
                    context.SaveChanges();
                    UpdateStatusTrip("\"" + comboBox10.Text + "\" eliminato");  
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
            dataGridView1.Rows.Clear();
            SvuotaCombo(1);
        }

        private void ComboBox6MouseClick(object sender, MouseEventArgs e)
        {
            RiempiComboUnit(comboBox6);
        }

        private void RiempiComboUnit(ComboBox combo)
        {
            combo.Items.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var r = from q in context.unita
                            select q.Nome;
                    _tutte = r.ToArray();
                    foreach (var s in r)
                        combo.Items.Add(PrimaM(s));
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private static void ErroreData(){
            ShowMessage("Data non valida", "Input non valido");
        }

        private void Button6Click(object sender, EventArgs e){
            var anno = numericUpDown5.Value;
            if(comboBox4.Text=="" || comboBox5.Text=="" || numericUpDown1.Value<=0) return;
            var oggi = DateTime.Now;
            var mese = numericUpDown4.Value;
            var giorno = numericUpDown3.Value;
            if ((mese == 11 || mese == 4 || mese == 6 || mese == 9) && giorno == 31){
                ErroreData();
                return;
            }
            if ((mese == 2) && ((anno % 4 == 0 && giorno >= 30) || (giorno >= 29 && anno % 4 != 0)))
            {
                ErroreData();
                return;
            }
            if (anno > oggi.Year)
            {
                ErroreData();
                return;
            }
            var data = new DateTime((int)anno, (int)mese, (int)giorno);
            if(data>oggi){
                ErroreData();
                return;
            }
            if(numericUpDown1.Value==0){
                ShowMessage("Non puoi donare 0 oggetti", "Input non valido");
                return;
            }
            var result1 = ShowMessageWithConfirm("Sei sicuro di donare?", "Conferma");
            if (result1 == DialogResult.No)
                return;
            try{
                using (var context=new DepositarioEntities()){
                    var item = from q in context.magazzino
                               where q.Item == comboBox5.Text.ToLower() && q.Unita==_unit
                               select q;
                    if(numericUpDown1.Value > item.First().Quanti){
                        ShowMessage("Non puoi donare così tanti oggetti! Non ne hai abbastanza!", "Input non valido");
                        return;
                    }
                    var nomeECognome = comboBox4.Text;
                    var t=new string[1];
                    t[0] = "  ";
                    var pezzi = nomeECognome.Split(t,StringSplitOptions.None);
                    var a = pezzi[1].ToLower();
                    var b = pezzi[0].ToLower();

                   

                    var ragazzo = from p in context.ragazzi
                                  where p.Cognome.Equals(a) && p.Nome.Equals(b)
                                  select p;
                    var d = new doni
                                {
                                          Data_i = data,
                                          Item = item.First().Id,
                                          Quanti = (int) numericUpDown1.Value,
                                          Ragazzo = ragazzo.First().ID,
                                          Unita = _unit
                                      };
                    item.First().Quanti -= (int) numericUpDown1.Value;
                    context.doni.Add(d);
                    context.SaveChanges();
                    UpdateStatusTrip("\"" + comboBox5.Text + "\" consegnato a " + comboBox4.Text);
                }
            }
            catch(System.Data.Entity.Infrastructure.DbUpdateException){
                ShowMessage("Dono già fatto", "Input non valido");
             }
            catch(Exception){
                ShowMessage(comboBox4.Text + comboBox5.Text, "");
                Errconnessione();
            }
            dataGridView1.Rows.Clear();
            comboBox4.Items.Clear();
            comboBox5.Items.Clear();
            numericUpDown1.Value = 1;
        }

        private void Button17Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.doni
                                   where q.Unita == _unit
                                   select new { q.magazzino.Item, q.Quanti, rag = q.ragazzi.Nome + " " + q.ragazzi.Cognome, q.Data_i };
                    foreach (var a in myEvents){
                        dataGridView1.Rows.Add();
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = PrimaM(a.Item);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = a.Quanti;
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = PrimaM(a.rag);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = a.Data_i.ToShortDateString();    
                    }
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void ComboBox7MouseClick(object sender, MouseEventArgs e)
        {
            CompletaRag(comboBox7);
        }

        private void ComboBox1MouseClick(object sender, MouseEventArgs e)
        {
            Completa(comboBox1);
        }

        private void Button16Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            if (comboBox1.Text == "" ) 
                return;
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.doni
                                   where q.magazzino.Item == comboBox1.Text.ToLower() && q.magazzino.Unita == _unit
                                   select new { q.magazzino.Item, q.Quanti, rag = q.ragazzi.Nome + " " + q.ragazzi.Cognome, q.Data_i };
                    UpdateStatusTrip(myEvents.Count() + " trovati");
                    foreach (var a in myEvents)
                    {
                        dataGridView1.Rows.Add();
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = PrimaM(a.Item);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = a.Quanti;
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = PrimaM(a.rag);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = a.Data_i.ToShortDateString();  
                    }
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void Button13Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            if (comboBox7.Text == "") return;
           var nomeECognome = comboBox7.Text;
                    var t=new string[1];
                    t[0] = "  ";
                    var pezzi = nomeECognome.Split(t,StringSplitOptions.None);
                    var a1 = pezzi[1];
                    var b = pezzi[0];
            try
            {
                using (var context = new DepositarioEntities()){
                    var myEvents = from q in context.doni
                                   where q.ragazzi.Nome == b.ToLower() && q.ragazzi.Cognome == a1.ToLower() && q.ragazzi.Unita == _unit
                                   select new { q.magazzino.Item, q.Quanti, rag = q.ragazzi.Nome + " " + q.ragazzi.Cognome, q.Data_i };
                    UpdateStatusTrip(myEvents.Count() + " trovati");
                    foreach (var a in myEvents)
                    {
                        dataGridView1.Rows.Add();
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = PrimaM(a.Item);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = a.Quanti;
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = PrimaM(a.rag);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = a.Data_i.ToShortDateString(); 
                    }
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void Button14Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            var data = new DateTime((int)numericUpDown8.Value, (int)numericUpDown7.Value, (int)numericUpDown6.Value);
            try{
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.doni
                                   where (radioButton1.Checked ? q.Data_i <= data : radioButton3.Checked ? q.Data_i == data : q.Data_i >= data) && q.magazzino.Unita == _unit
                                   select new { q.magazzino.Item, q.Quanti, rag = q.ragazzi.Nome + " " + q.ragazzi.Cognome, q.Data_i };
                    foreach (var a in myEvents)
                    {
                        dataGridView1.Rows.Add();
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = PrimaM(a.Item);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = a.Quanti;
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = PrimaM(a.rag);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = a.Data_i.ToShortDateString();
                    }
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void ComboBox10MouseClick(object sender, MouseEventArgs e)
        {
            CompletaRag(comboBox10);
        }

        private void ComboBox9MouseClick(object sender, MouseEventArgs e)
        {
            CompletaRag(comboBox9);
        }

        private void Button9Click(object sender, EventArgs e)
        {
            if (comboBox9.Text == "" || comboBox6.Text=="")
                return;
            var result1 = ShowMessageWithConfirm("Sei sicuro di cancellare " + comboBox9.Text + "?", "Conferma");
            if (result1 == DialogResult.No)
                return;
            var nomeECognome = comboBox9.Text;
            var t = new string[1];
            t[0] = "  ";
            var pezzi = nomeECognome.Split(t, StringSplitOptions.None);
            var a1 = pezzi[1];
            var b = pezzi[0];
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var r = (from q in context.ragazzi
                             where q.Nome == b.ToLower() && q.Cognome == a1.ToLower() && q.Unita == _unit
                             select q);
                    r.First().Unita = comboBox6.Text;
                    context.SaveChanges();
                    UpdateStatusTrip("\"" + comboBox9.Text + "\" spostato in " + comboBox6.Text);
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
            dataGridView1.Rows.Clear();
            SvuotaCombo(1);
        }
        
        private void DataGridView1CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {

            if (dataGridView1.SelectedCells[0].Value==null)
            {
                _content = null;
                return;
            }
            //var sgf = dataGridView1.SelectedCells[0].Value;
            //if(dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].HeaderCell.ToString()=="Censito")
            //    _content= (!(bool)dataGridView1.SelectedCells[0].Value).ToString().ToLower();
            _content = dataGridView1.SelectedCells[0].Value.ToString().ToLower();
            _x =dataGridView1.CurrentCell.RowIndex;
            _y = dataGridView1.CurrentCell.ColumnIndex;

        }

        private void DataGridView1CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (_content == null || dataGridView1[_y, _x].Value==null) return;
            if (dataGridView1[_y, _x].Value.ToString().ToLower() == _content)
            {
                dataGridView1.CurrentCell.Value = PrimaM(_content);
                return;
            }
            switch (tabControl2.SelectedIndex)
            {
                case 0:
                    var result = ShowMessageWithConfirm("Sei sicuro di modificare?","Conferma");
                    if(result == DialogResult.No)
                    {
                        dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex].Value=PrimaM(_content);
                        return;
                    }
                    try
                    {
                        var cont = dataGridView1.CurrentCell.Value.ToString().ToLower();
                        var a = long.Parse(dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString());
                        using (var context = new DepositarioEntities())
                        {
                            var r = (from q in context.magazzino
                                     where q.Id == a &&
                                     q.Unita == _unit
                                     select q);
                            r.First().Item = cont;
                            context.SaveChanges();
                            UpdateStatusTrip("Dato modificato");
                        }
                    }
                    catch (System.Data.Entity.Infrastructure.DbUpdateException)
                    {
                        ShowMessage("Modifica non valida: Item gia' presente", "Input non valido");
                    }
                    catch (Exception)
                    {
                        dataGridView1.CurrentCell.Value = PrimaM(_content);
                        Errconnessione();
                    }
                    break;
                case 1:
                    var i = 0;
                    if(dataGridView1.SelectedCells[0].ColumnIndex==0 && !Int32.TryParse(dataGridView1.SelectedCells[0].Value.ToString(),out i))
                    {
                        dataGridView1.CurrentCell.Value = PrimaM(_content);
                        ShowMessage("Devi inserire un numero!", "Errore in input");
                        return;
                    }
                    var result1 = ShowMessageWithConfirm("Sei sicuro di modificare?","Conferma");
                    if(result1 == DialogResult.No)
                    {
                        dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex].Value=PrimaM(_content);
                        return;
                    }
                    try
                    {
                        var cont = dataGridView1.CurrentCell.Value.ToString().ToLower();
                        var a = dataGridView1[1,dataGridView1.CurrentCell.RowIndex].Value.ToString().ToLower();
                        var b = dataGridView1[2,dataGridView1.CurrentCell.RowIndex].Value.ToString().ToLower();
                        using (var context = new DepositarioEntities())
                        {
                            var r =  (from q in context.ragazzi
                                     where 
                                     (dataGridView1.CurrentCell.ColumnIndex==0?
                                     q.Nome == a && 
                                     q.Cognome == b
                                     : 
                                     dataGridView1.CurrentCell.ColumnIndex==1?
                                     q.Nome == _content && 
                                     q.Cognome == b 
                                     :
                                     dataGridView1.CurrentCell.ColumnIndex==2?
                                     q.Nome == a &&
                                     q.Cognome == _content
                                     :
                                     q.Nome == a &&
                                     q.Cognome == b ) && 
                                     q.Unita == _unit
                                     select q);
                            switch(dataGridView1.CurrentCell.ColumnIndex)
                            {
                                case 0:
                                    r.First().Codice = i;
                                    break;
                                case 1:
                                    r.First().Nome = cont;
                                    break;
                                case 2:
                                    r.First().Cognome = cont;
                                    break;
                                case 3:
                                    r.First().Censimento = !r.First().Censimento;
                                    break;
                            }
                            context.SaveChanges();
                            UpdateStatusTrip("Dato modificato");
                        }
                    }
                    catch (System.Data.Entity.Infrastructure.DbUpdateException)
                    {
                        ShowMessage("Modifica non valida: Utente gia' presente", "Input non valido");
                    }
                    catch (Exception)
                    {
                        dataGridView1.CurrentCell.Value = PrimaM(_content);
                        Errconnessione();
                    }
                    break;
            }
            dataGridView1.CurrentCell.Value = PrimaM(dataGridView1.CurrentCell.Value.ToString());
        }

        private static string PrimaM (string a)
        {
            a = a.ToLower();
            var b = new char[a.Length];
            b[0] = char.ToUpper(a.First());
            for (var i = 1; i < a.Length; i++)
            {
                b[i] = (b[i - 1] == ' ' ? char.ToUpper(a[i]) : a[i]);
            }
            return new string(b);
        }

        private void ComboBox8SelectedIndexChanged(object sender, EventArgs e)
        {
            _unit = comboBox8.Text;
            dataGridView1.Rows.Clear();
            SvuotaComboAll();
        }

        private void TextBox1KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button2Click(null,null);
        }

        private void TextBox3KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button4Click(null, null);
        }

        private void ComboBox3KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button5Click(null, null);
        }

        private void NumericUpDown2KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button7Click(null, null);
        }

        private void TextBox7KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button12Click(null, null);
        }

        private void TextBox10KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button8Click(null, null);
        }

        private void TextBox11KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button8Click(null, null);
        }

        private void ComboBox10KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button10Click(null, null);
        }

        private void ComboBox6KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button9Click(null, null);
        }

        private void ComboBox1KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button16Click(null, null);
        }

        private void ComboBox7KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button13Click(null, null);
        }

        private void NumericUpDown8KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button14Click(null, null);
        }

        private void TextBox8KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Button12Click(null, null);
        }

        private void Label4Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                ShowMessage("La tabella e' vuota non ti salvo niente.","Fermo!");
                return;
            }

            var saveFileDialog1 = new SaveFileDialog
            {
                InitialDirectory = Application.StartupPath,
                Filter = @"xls files (*.xls)|*.xls",
                Title = @"Save an Excel File"
            };
            try
            {
                saveFileDialog1.ShowDialog();
            }
            catch (Exception)
            {
                ShowMessage("Il file e' in uso da un altro programma!", "Errore");
                return;
            }
            if (saveFileDialog1.FileName == "")
                return;
           var fileStream = saveFileDialog1.OpenFile();
            Scrivi(fileStream);
        }
       

        private void Scrivi(Stream fileStream)
        {
            var tw = new StreamWriter(fileStream);

            for (var i = 0; i < dataGridView1.Columns.Count; i++)
            {
                    tw.Write(dataGridView1.Columns[i].HeaderText +"\t");
            }
            tw.WriteLine();
            for (var i = 0; i < dataGridView1.Rows.Count; i++)
            {
                var temp = "";
                for (var j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    temp += dataGridView1[j, i].Value +"\t";
                }
                tw.WriteLine(temp);   
            }
            tw.Close();
        }
        private void TextBox4Enter(object sender, EventArgs e)
        {
            textBox4.SelectAll();
        }

        private void TextBox4Click(object sender, EventArgs e)
        {
            textBox4.SelectAll();
        }

        private void TextBox3Enter(object sender, EventArgs e)
        {
            textBox3.SelectAll();
        }

        private void TextBox3Click(object sender, EventArgs e)
        {
            textBox3.SelectAll();
        }

        private void TextBox1Click(object sender, EventArgs e)
        {
            textBox1.SelectAll();
        }

        private void TextBox1Enter(object sender, EventArgs e)
        {
            textBox1.SelectAll();
        }

        private void TextBox5Click(object sender, EventArgs e)
        {
            textBox5.SelectAll();
        }

        private void TextBox5Enter(object sender, EventArgs e)
        {
            textBox5.SelectAll();
        }

        private void TextBox8Click(object sender, EventArgs e)
        {
            textBox8.SelectAll();
        }

        private void TextBox8Enter(object sender, EventArgs e)
        {
            textBox8.SelectAll();
        }

        private void TextBox7Click(object sender, EventArgs e)
        {
            textBox7.SelectAll();
        }

        private void TextBox7Enter(object sender, EventArgs e)
        {
            textBox7.SelectAll();
        }

        private void TextBox6Click(object sender, EventArgs e)
        {
            textBox6.SelectAll();
        }

        private void TextBox6Enter(object sender, EventArgs e)
        {
            textBox6.SelectAll();
        }

        private void TextBox10Enter(object sender, EventArgs e)
        {
            textBox10.SelectAll();
        }

        private void TextBox10Click(object sender, EventArgs e)
        {
            textBox10.SelectAll();
        }

        private void TextBox11Click(object sender, EventArgs e)
        {
            textBox11.SelectAll();
        }

        private void TextBox11Enter(object sender, EventArgs e)
        {
            textBox11.SelectAll();
        }

        private void NumericUpDown1Enter(object sender, EventArgs e)
        {
            numericUpDown1.Select(0, numericUpDown1.Text.Length);
        }

        private void NumericUpDown1Click(object sender, EventArgs e)
        {
            numericUpDown1.Select(0, numericUpDown1.Text.Length);
        }

        private void NumericUpDown3Click(object sender, EventArgs e)
        {
            numericUpDown3.Select(0, numericUpDown3.Text.Length);
        }

        private void NumericUpDown3Enter(object sender, EventArgs e)
        {
            numericUpDown3.Select(0, numericUpDown3.Text.Length);
        }

        private void NumericUpDown4Click(object sender, EventArgs e)
        {
            numericUpDown4.Select(0, numericUpDown4.Text.Length);
        }

        private void NumericUpDown4Enter(object sender, EventArgs e)
        {
            numericUpDown4.Select(0, numericUpDown4.Text.Length);
        }

        private void NumericUpDown5Enter(object sender, EventArgs e)
        {
            numericUpDown5.Select(0, numericUpDown5.Text.Length);
        }

        private void NumericUpDown5Click(object sender, EventArgs e)
        {
            numericUpDown5.Select(0, numericUpDown5.Text.Length);
        }

        private void NumericUpDown2Click(object sender, EventArgs e)
        {
            numericUpDown2.Select(0, numericUpDown2.Text.Length);
        }

        private void NumericUpDown2Enter(object sender, EventArgs e)
        {
            numericUpDown2.Select(0, numericUpDown2.Text.Length);
        }

        private void NumericUpDown6Click(object sender, EventArgs e)
        {
            numericUpDown6.Select(0, numericUpDown6.Text.Length);
        }

        private void NumericUpDown6Enter(object sender, EventArgs e)
        {
            numericUpDown6.Select(0, numericUpDown6.Text.Length);
        }

        private void NumericUpDown7Click(object sender, EventArgs e)
        {
            numericUpDown7.Select(0, numericUpDown7.Text.Length);
        }

        private void NumericUpDown7Enter(object sender, EventArgs e)
        {
            numericUpDown7.Select(0, numericUpDown7.Text.Length);
        }

        private void NumericUpDown8Click(object sender, EventArgs e)
        {
            numericUpDown8.Select(0, numericUpDown8.Text.Length);
        }

        private void NumericUpDown8Enter(object sender, EventArgs e)
        {
            numericUpDown8.Select(0, numericUpDown8.Text.Length);
        }

        private void ComboBox2SelectedIndexChanged(object sender, EventArgs e)
        {
            label20.Visible = comboBox2.SelectedIndex == 2;
        }

        private void SvuotaCombo(int a)
        {
            switch (a)
            {
                case 0:
                    comboBox3.Items.Clear();
                    comboBox4.Items.Clear();
                    comboBox5.Items.Clear();
                    break;
                case 1:
                    comboBox6.Items.Clear();
                    comboBox9.Items.Clear();
                    comboBox10.Items.Clear();
                    break;
                case 3:
                    comboBox1.Items.Clear();
                    comboBox7.Items.Clear();
                    break;
            }
        }

        private void SvuotaComboAll()
        {
            comboBox3.Items.Clear();
            comboBox4.Items.Clear();
            comboBox5.Items.Clear();
            comboBox6.Items.Clear();
            comboBox9.Items.Clear();
            comboBox10.Items.Clear();
            comboBox1.Items.Clear();
            comboBox7.Items.Clear();
        }

        private void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            switch (e.Argument.ToString())
            {
                case "login":
                    #region
                        if (button4.Text != "Connetti") return;
                        var buffer = new ASCIIEncoding().GetBytes(textBox3.Text);
                        var cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
                        var r = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "").ToLower();
                        try
                        {
                            using (var context = new DepositarioEntities())
                            {
                                var rr = from q in context.utenti
                                         where q.User == textBox4.Text && q.Pwd == r && q.Attivo
                                         select q;
                                if (!rr.Any())
                                {
                                    ShowMessage("Utente o Password non valide!", "Errore Login");
                                    return;
                                }
                                _unit = rr.First().Unita;
                                _capoGruppo = rr.First().Capogruppo;
                            }
                            e.Result = "login";
                        }
                        catch (Exception)
                        {
                            Errconnessione();
                            e.Result = "login+err";
                        }
                     #endregion
                    break;
            }
        }

        private void BackgroundWorker1RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            statusStrip1.Items[0].Text = "";
            button4.Enabled = true;
            if (e.Result == null) return;
            var ris = e.Result.ToString().Split('+');
            switch (ris[0])
            {
                case "login":
                    #region
                    button4.Enabled = true;
                    if (ris.Length>1 && ris[1].Equals("err")) return;
                    UpdateStatusTrip(textBox4.Text + " connesso");
                    tabControl1.TabPages[0].Text = "Logout";
                    tabControl1.TabPages[1].Enabled = true;
                    tabControl1.SelectedIndex = 1;
                    textBox3.Enabled = false;
                    textBox4.Enabled = false;
                    button4.Text = "Disconnetti";
                    comboBox8.Items.Clear();
                    if (_capoGruppo)
                    {
                        RiempiComboUnit(comboBox8);
                        var i = 0;
                        for (; i < _tutte.Length; i++)
                        {
                            if (_tutte[i].Equals(_unit))
                                break;
                        }
                        comboBox8.SelectedIndex = i;
                    }
                    else
                    {
                        comboBox8.Items.Add(_unit);
                        comboBox8.SelectedIndex = 0;
                    }
                    #endregion
                    break;
            }
           
        }

        private void Button3Click(object sender, EventArgs e)
        {
            FindCensiti(true);
        }

        private void Button15Click(object sender, EventArgs e)
        {
            FindCensiti(false);
        }

        private void FindCensiti(bool yes)
        {
            dataGridView1.Rows.Clear();
            try
            {
                using (var context = new DepositarioEntities())
                {
                    var myEvents = from q in context.ragazzi
                                   where q.Unita == _unit && q.Censimento==yes
                                   select q;
                    RiempiTabRagazzi(myEvents);
                }
            }
            catch (Exception)
            {
                Errconnessione();
            }
        }

        private void Form1SizeChanged(object sender, EventArgs e)
        {
            var y = groupBox6.Height +
           ((groupBox5.Location.Y + groupBox5.Height) / 2 - groupBox6.Height - groupBox1.Height) / 2;
            var y2 = (groupBox5.Location.Y + groupBox5.Height) / 2 +
            ((groupBox5.Location.Y + groupBox5.Height) / 2 - groupBox5.Height - groupBox4.Height) / 2;
            groupBox1.Location = y > 110 ? new Point(7, y) : new Point(7, 110);
            if (y2 > 221)
                groupBox4.Location = new Point(7, y2);

            var ya = groupBox7.Height +
            ((groupBox8.Location.Y + groupBox8.Height) / 2 - groupBox7.Height - groupBox10.Height) / 2;
            var y2a = (groupBox8.Location.Y + groupBox8.Height) / 2 +
            ((groupBox8.Location.Y + groupBox8.Height) / 2 - groupBox8.Height - groupBox9.Height) / 2;
            groupBox10.Location = ya>110 ? new Point(7, ya) : new Point(7, 110);
            if (y2a > 221)
                groupBox9.Location = new Point(7, y2a);
        }
    }
}